package com.way.activity;

import java.io.BufferedOutputStream;
import java.io.File;
import java.io.FileOutputStream;
import java.io.IOException;
import java.io.UnsupportedEncodingException;
import java.util.Date;
import java.util.Random;

import javax.crypto.SecretKey;

import android.graphics.Bitmap;
import android.graphics.Matrix;
import android.graphics.drawable.BitmapDrawable;
import android.os.Bundle;
import android.os.Environment;
import android.text.TextUtils;
import android.view.View;
import android.view.View.OnClickListener;
import android.widget.Button;
import android.widget.ImageView;
import android.widget.Toast;

import com.actionbarsherlock.view.Menu;
import com.actionbarsherlock.view.MenuItem;
import com.google.zxing.BarcodeFormat;
import com.google.zxing.MultiFormatWriter;
import com.google.zxing.WriterException;
import com.google.zxing.common.BitMatrix;
import com.way.app.App;
import com.way.qrcode.R;
import com.way.swipeback.SwipeBackActivity;
import com.way.util.DesEncrypt;
import com.way.util.L;
import com.way.util.T;

public class EditQRActivity extends SwipeBackActivity implements
		OnClickListener {
	private static final int IMAGE_HALFWIDTH = 20;
	// ---二维码的颜色
	private static final int COLOR_BLUE = 0xFF3366CC;
	private static final int COLOR_RED = 0xFFFD3C3C;
	private static final int COLOR_PURPLE = 0xFF68228B;
	private static final int COLOR_BLACK = 0xEE000000;
	private static final int[] COLORS = { COLOR_BLUE, COLOR_RED, COLOR_PURPLE,
			COLOR_BLACK };

	private static final int STYLE_SIMPLE = 0;
	private static final int STYLE_COLORS = 1;
	private static final int STYLE_FLOWER = 2;

	private App mApp;
	// 判断保存的二维码是否一样
	private Bitmap mLastSaveBitmap = null;

	// 显示生成二维码图像
	private ImageView mQRView;
	private ImageView mQRStyleBtn1;
	private ImageView mQRStyleBtn2;
	private ImageView mQRStyleBtn3;
	private Button mQRLogoBtn;
	private String mContent;// 二维码内容
	
	private boolean isShowLogo;
	// 二维码颜色
	private int mQRColor;
	private int mQRStyle;
	private int mClickCount;
	// 保存生成的二维码
	private Bitmap mQRBitmap = null;

	// 插入到二维码里面的图片对象
	private Bitmap mLogoInsideBitmap;

	@Override
	protected void onCreate(Bundle savedInstanceState) {
		super.onCreate(savedInstanceState);
		setContentView(R.layout.edit_qrcode_layout);
		getSupportActionBar().setDisplayHomeAsUpEnabled(true);
		mApp = App.getApp();
		mContent = getIntent().getStringExtra("content");
		initViews();
	}

	@Override
	public boolean onCreateOptionsMenu(Menu menu) {
		getSupportMenuInflater().inflate(R.menu.main, menu);
		return super.onCreateOptionsMenu(menu);
	}

	@Override
	public boolean onOptionsItemSelected(MenuItem item) {
		if (item.getItemId() == R.id.action_save_to_file) {

			try {
				if (mQRBitmap == null || TextUtils.isEmpty(mContent)) {
					T.showShort(this, "图片或字符串有误，无法保存！");
					return true;
				}

				if (mLastSaveBitmap != null && mLastSaveBitmap == mQRBitmap) {
					T.showShort(this, "刚刚保存过此二维码");
					return true;
				}
				String result = saveFile(mQRBitmap, mContent);
				// 保存之后，将此次保存的字符串和图片暂存一下
				mLastSaveBitmap = mQRBitmap;
				if (result != null) {
					T.showShort(this, "已保存至SD卡：" + result);
				}
			} catch (IOException e) {
				e.printStackTrace();
				T.showShort(this, "保存至SD卡失败！");
			}

		}
		return true;
	}

	private void initViews() {

		mQRView = (ImageView) findViewById(R.id.iv_QRbmp);
		mQRStyleBtn1 = (ImageView) findViewById(R.id.iv_colorQR1);
		mQRStyleBtn2 = (ImageView) findViewById(R.id.iv_colorQR2);
		mQRStyleBtn3 = (ImageView) findViewById(R.id.iv_colorQR3);
		mQRLogoBtn = (Button) findViewById(R.id.view_qrcode_btn);
		mQRStyleBtn1.setOnClickListener(this);
		mQRStyleBtn2.setOnClickListener(this);
		mQRStyleBtn3.setOnClickListener(this);
		mQRLogoBtn.setOnClickListener(this);

		mQRStyle = STYLE_SIMPLE;
		mQRColor = COLOR_BLACK;
		isShowLogo = false;
		mQRLogoBtn.setText("显示Logo");
		mQRStyleBtn1.setBackgroundColor(mQRColor);
		if (!TextUtils.isEmpty(mContent)) {
			mCreateQRcode(mContent, mQRStyle);
		}
	}

	public void mCreateQRcode(String qrStr, int qrStyle) {

		if (TextUtils.isEmpty(qrStr)) {
			T.showShort(this, R.string.QRCreate_noContent);
			return;
		}

		// 构造需要插入的图片对象
		mLogoInsideBitmap = ((BitmapDrawable) getResources().getDrawable(
				R.drawable.ic_launcher)).getBitmap();
		// 缩放图片
		Matrix m = new Matrix();
		float sx = (float) 2 * IMAGE_HALFWIDTH / mLogoInsideBitmap.getWidth();
		float sy = (float) 2 * IMAGE_HALFWIDTH / mLogoInsideBitmap.getHeight();

		m.setScale(sx, sy);
		// 重新构造一个40*40的图片
		mLogoInsideBitmap = Bitmap.createBitmap(mLogoInsideBitmap, 0, 0,
				mLogoInsideBitmap.getWidth(), mLogoInsideBitmap.getHeight(), m,
				false);

		try {
			// s.getBytes();使用系统默认字符集(UTF-8)将字符串编码成字节型数组
			Bitmap bm = createQRBmp(new String(qrStr.getBytes(), "ISO-8859-1"),
					qrStyle);
			if (bm != null)
				mQRView.setImageBitmap(bm);

		} catch (WriterException e) {
			e.printStackTrace();
		} catch (UnsupportedEncodingException e) {
			e.printStackTrace();
		}
	}

	/**
	 * 
	 * @param str
	 *            需要生成二维码的字符串
	 * @return 将生成的二维码转换成Bitmap并返回
	 * @throws WriterException
	 */
	public Bitmap createQRBmp(String str, int qrStyle) throws WriterException {
		// 生成二维矩阵,编码时指定大小,不要生成了图片以后再进行缩放,这样会模糊导致识别失败
		// 返回BitMatrix对象，其实就是一个布尔型的数组
		// encode()方法穿传入的参数：1、编码的字符串 2、编码的类型(二维码，条形码...) 3、返回数组的大小(类似于分辨率)
		SecretKey key = mApp.getSecretKey();
		if (key == null) {
			T.showShort(this, "密钥不存在，无法生成二维码");
			return null;
		}
		//对二维码信息加密
		str = DesEncrypt.getEncString(str, key);

		BitMatrix matrix = new MultiFormatWriter().encode(str,
				BarcodeFormat.QR_CODE, 300, 300);
		int width = matrix.getWidth();
		int height = matrix.getHeight();
		// 二维矩阵转为一维像素数组,也就是一直横着排了
		int halfW = width / 2;
		int halfH = height / 2;
		int[] pixels = new int[width * height];

		int a = -150;
		int b = 150;
		int c = 150;
		int d = 450;
		Random random = new Random();
		int leftTop = COLORS[random.nextInt(4)];
		int leftBottom = COLORS[random.nextInt(4)];
		int rightTop = COLORS[random.nextInt(4)];
		int rightBottom = COLORS[random.nextInt(4)];
		int center = COLORS[random.nextInt(4)];
		L.i(leftTop + ":" + leftBottom + ":" + rightTop + ":" + rightBottom
				+ ":" + center);

		for (int y = 0; y < height; y++) {
			for (int x = 0; x < width; x++) {

				// 将图片绘制到指定区域中
				// 就是将图片像素的颜色值写入到相应下标的数组中
				if (x > halfW - IMAGE_HALFWIDTH && x < halfW + IMAGE_HALFWIDTH
						&& y > halfH - IMAGE_HALFWIDTH
						&& y < halfH + IMAGE_HALFWIDTH && isShowLogo) {
					pixels[y * width + x] = mLogoInsideBitmap.getPixel(x
							- halfW + IMAGE_HALFWIDTH, y - halfH
							+ IMAGE_HALFWIDTH);
				} else {
					// 判断当前位置在二维矩阵中存储的boolean值
					if (matrix.get(x, y)) {

						if (qrStyle == 1) {
							// ---左下角
							if (y >= 150 && x <= a) {
								mQRColor = leftBottom;

								// ---右上角
							} else if (y <= 150 && x >= b) {
								mQRColor = rightTop;

								// ---左上角
							} else if (y <= 150 && x <= c) {
								mQRColor = leftTop;

								// ---右下角
							} else if (y >= 150 && x >= d) {
								mQRColor = rightBottom;

							} else {
								mQRColor = center;
							}
						} else if (qrStyle == 2) {
							mQRColor = COLORS[random.nextInt(4)];
						}

						pixels[y * width + x] = mQRColor;

					} else {

						pixels[y * width + x] = 0xffffffff;

					}
				}

			}
			a++;
			b++;
			c--;
			d--;
		}

		Bitmap bitmap = Bitmap.createBitmap(width, height,
				Bitmap.Config.ARGB_8888);
		// 通过像素数组生成bitmap
		bitmap.setPixels(pixels, 0, width, 0, 0, width, height);

		mQRBitmap = bitmap;
		return bitmap;

	}

	public String saveFile(Bitmap qrBmp, String qrStr) throws IOException {
		// 首先判断SD卡存在
		if (!Environment.MEDIA_MOUNTED.equals(Environment
				.getExternalStorageState())) {
			T.showShort(this, "无法识别SD卡!");
			return null;
		} else {
			long fileNamePath = new Date().getTime();
			// 创建目录
			File fileDir = new File(Environment.getExternalStorageDirectory(),
					File.separator + "QRCode" + File.separator);
			if (!fileDir.exists()) {
				fileDir.mkdirs();
			}
			// 创建文件
			File jpgFile = new File(fileDir.getAbsolutePath() + File.separator
					+ fileNamePath + ".JPG");
			if (!jpgFile.exists()) {
				jpgFile.createNewFile();
			}
			BufferedOutputStream bosPNG = new BufferedOutputStream(
					new FileOutputStream(jpgFile));
			qrBmp.compress(Bitmap.CompressFormat.JPEG, 80, bosPNG);
			bosPNG.flush();
			bosPNG.close();
			return fileDir.getPath() + fileNamePath;
		}

	}

	@Override
	public void onClick(View v) {
		switch (v.getId()) {
		case R.id.iv_colorQR1:
			mQRStyle = STYLE_SIMPLE;
			mClickCount++;
			mQRColor = COLORS[mClickCount % 4];
			mQRStyleBtn1.setBackgroundColor(mQRColor);
			break;
		case R.id.iv_colorQR2:
			mQRStyle = STYLE_COLORS;
			break;
		case R.id.iv_colorQR3:
			mQRStyle = STYLE_FLOWER;
			break;
		case R.id.view_qrcode_btn:
			isShowLogo = !isShowLogo;
			if(isShowLogo)
				mQRLogoBtn.setText("隐藏Logo");
			else
				mQRLogoBtn.setText("显示Logo");
			break;
		default:
			break;
		}
		if (!TextUtils.isEmpty(mContent)) {
			mCreateQRcode(mContent, mQRStyle);
		}
	}
}
